package com.ruoyi.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.conditions.update.LambdaUpdateChainWrapper;
import com.ruoyi.system.domain.SysUserRole;
import com.ruoyi.system.mapper.SysUserRoleMapper;
import com.ruoyi.system.service.ISysUserRoleService;
import org.apache.ibatis.executor.BatchResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class SysUserRoleServiceImpl implements ISysUserRoleService {
    @Autowired
    private SysUserRoleMapper userRoleMapper;

    @Override
    public List<SysUserRole> selectByUserId(Long userId) {
        LambdaQueryWrapper<SysUserRole> queryWrapper = new LambdaQueryWrapper<SysUserRole>().eq(SysUserRole::getUserId, userId);
        return userRoleMapper.selectList(queryWrapper);
    }

    @Override
    public int deleteByUserId(Long userId) {
        LambdaUpdateWrapper<SysUserRole> updateWrapper = new LambdaUpdateWrapper<SysUserRole>()
                .eq(SysUserRole::getUserId, userId);
        return userRoleMapper.delete(updateWrapper);
    }

    @Override
    public void deleteByUserIds(Long[] userIds) {
        new LambdaUpdateChainWrapper<>(userRoleMapper)
                .in(SysUserRole::getUserId, userIds)
                .remove();
    }

    @Override
    public boolean delete(SysUserRole userRole) {
        return new LambdaUpdateChainWrapper<SysUserRole>(userRoleMapper)
                .eq(SysUserRole::getUserId, userRole.getUserId())
                .eq(SysUserRole::getRoleId, userRole.getRoleId())
                .remove();
    }

    @Override
    @Transactional
    public boolean deleteBatch(Long roleId, Long[] userIds) {
        return new LambdaUpdateChainWrapper<>(userRoleMapper)
                .in(SysUserRole::getUserId, userIds)
                .eq(SysUserRole::getRoleId, roleId)
                .remove();
    }

    @Override
    public int saveList(List<SysUserRole> list) {
        List<BatchResult> insert = userRoleMapper.insert(list);
        return insert.size();
    }

    @Override
    public List<SysUserRole> selectByRoleId(Long roleId) {
        return new LambdaQueryChainWrapper<>(userRoleMapper)
                .eq(SysUserRole::getRoleId, roleId)
                .list();
    }

    @Override
    public List<SysUserRole> selectNotEQRoleId(Long roleId) {
        return new LambdaQueryChainWrapper<>(userRoleMapper)
                .ne(SysUserRole::getRoleId, roleId)
                .list();
    }
}
